import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/cms/cmsdialogscreen.dart';
import 'package:opene/ui/cms/cmsmodel.dart';
import 'package:opene/ui/cms/oblpn/cmsoblpnsubmitscreen.dart';
import 'package:opene/ui/cms/tally/cmstallysubmitscreen.dart';
import 'package:toast/toast.dart';

class CMSOBLPNScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CMSOBLPNScreenPage();
  }
}

class CMSOBLPNScreenPage extends StatefulWidget {
  @override
  _CMSOBLPNScreenPageState createState() => _CMSOBLPNScreenPageState();
}

class _CMSOBLPNScreenPageState extends BaseState<CMSOBLPNScreenPage> {
  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<CMSOBLPN> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "OutBoundLPN";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 5, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                flex: 2, //设置权重
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "BOL NO",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Text(
                            "Dest",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                          ),
                        ),
                        Text(
                          "Expected",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                        ),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(width: 5,),
              GestureDetector(
                onTap: () {
                  type = 1;
                  // getWarehousingDetailTallyInfo(tally);
                },
                child: Container(
                  padding: EdgeInsets.all(3),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Colors.transparent, // 背景颜色
                    borderRadius: BorderRadius.all(Radius.circular(5)), // 圆角半径
                    border: Border.all(
                      color: Colors.transparent, // 边框颜色
                      width: 0.5, // 边框宽度
                    ),
                  ),
                  child: Text(
                    'Complete',
                    style: TextStyle(color: Colors.transparent, fontSize: 14.0),
                  ), // 子控件，如果需要的话
                ),
              ),
            ],
          ),
          Expanded(
            child: setListView(),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        CMSOBLPN tally = data[index];
        return Column(
          children: [
            Visibility(
              visible: index==0?true:false,
                child: SizedBox(height: 5,)),
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // getWarehousingDetailTallyInfo(tally);
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => CMSOBLPNSubmitScreen(cmsoblpn:tally)),
                      );
                    },
                    child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        Utils.getStringisEmpty(tally.bolNumber),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                      ),
                      Row(
                        children: [
                          Expanded(
                            flex: 1,
                            child: Text(
                              Utils.getStringisEmpty(tally.destination),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                            ),
                          ),
                          Text(tally.deliveryDate==null?"":
                          Utils.getStringisEmpty(tally.deliveryDate),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                          ),
                        ],
                      )
                    ],
                  ),),
                ),
                SizedBox(width: 5,),
                GestureDetector(
                  onTap: () {
                    getWarehousingDetailTallyInfo(tally);
                  },
                  child: Container(
                    padding: EdgeInsets.all(3),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.nearlyBlue, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(5)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: TextStyle(color: Colors.white, fontSize: 14.0),
                    ), // 子控件，如果需要的话
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    // if (Utils.isEmpty(strDate)) {
    //   Toast.show("Please select Drop Date", duration: Toast.lengthShort, gravity: Toast.bottom);
    //   return;
    // }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void getTallyContainerNo() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.outLoadingV2PendingContainers);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => CMSOBLPN.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void getWarehousingDetailTallyInfo(CMSOBLPN tally) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.outLoadingV2Info+"/${tally.id}");

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {

      List<CMSOBLPNDetails> cmsOBLPNDetailsList = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => CMSOBLPNDetails.fromJson(userJson)).toList());

      if (cmsOBLPNDetailsList == null) {
        return;
      }

      showDialog(
        context: context,
        builder: (context) => CMSOBLPNDetailDialog(tally: tally, tallyDetails: cmsOBLPNDetailsList),
      ).then((value) => {
            if (value != null && value) {tallyFinish(tally.id)}
          });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void tallyFinish(int id) async {
    CMSOBLPNComplete containerTallyQr = new CMSOBLPNComplete();
    containerTallyQr.id = id;
    // 显示加载中对话框
    LoadingIndicator.show(context,title: "Complete...");
    String json = jsonEncode(containerTallyQr);
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.outLoadingV2Complete, method: BaseMethod.post,data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      getTallyContainerNo();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
